<template>
    <div style="height: 100%;" ref="contentRef">
        <navbar :title="$t('mod_exit_save')"></navbar>
        <div class="content-noBottom">
            <div class="s-content">
              <div class="con-box">
                <div class="con-box-head">
                  <h2>{{formData.rcrTitle}}</h2>
                  <div class="author-msg">{{formData.usrDisplayBil}}<span style="margin-left: 20px">{{formData.scUpdateTime}}</span></div>
                </div>
                <div v-for="(item, index) in formData.passageList" :key="index">
                <div v-for="(itm, ind) in selectList[formData.scType - 1].order" :key="ind">
                  <img :src="appUrl + item.scpSrcLink"  v-if="itm === 'pic'" class="con-box-img">
                    <xg-player v-if="itm === 'video'&&item.scpType=='VOD'" :videoConfig="getVideoConfig(item)"></xg-player>
                  <audio :src="appUrl + item.scpSrcLink"  v-if="itm === 'video'&&item.scpType=='AUD'" class="con-box-audio" preload  controls="controls"></audio>
                  <div  v-if="itm === 'text'" v-html="$xss(item.scpContent)" class="con-box-text"></div>
                </div>
              </div>
              </div>
            </div>
        </div>
        <verification-code v-if="isHandUp" @overtime-code="handleOverTime" @pass-code="passCode"></verification-code>
    </div>
</template>

<script>
import { getDate } from '@/utils/tools';
import verificationCode from '@/repeatComponents/verification-code/verification-code';
import xgPlayer from '@/components/player/xgplayer';
export default {
    name: 'sclassConent',
    components: {xgPlayer, verificationCode},
    data() {
        return {
            isHide: false,
            videoKey: 1,
            curTime: 0, // 最后一次播放时间点
            player: {},
            overTime: false, // 是否超时
            isHandUp: false,
            modHangUpTime: 0, // 防挂机间隔时间
            handTimer: {}, // 定时器
            handTimes: 0, // 定时器初始时间（s）
            handCurTime: 0, // 视频断点上一次续播时间（用于防挂机）
            data: {},
            formData: {},
            startTime: new Date().getTime(),
            load: false,
            curLan: window.localStorage.getItem('globalLang'),
            modId: this.$route.params.modId,
            palpitate: {
                isPause: false, // 是否暂停
                itmId: '', // 课程itmId
                modId: '', // 模块resId
                tkhId: '' // 学习跟踪id
            },
            times: null,
            selectList: [
                {
                    type: 1,
                    title: this.$t('resource.pic_text') + '1',
                    order: ['pic', 'text']
                },
                {
                    type: 2,
                    title: this.$t('resource.pic_text') + '2',
                    order: ['text', 'pic']
                },
                {
                    type: 3,
                    title: this.$t('resource.video_text') + '1',
                    order: ['video', 'text']
                },
                {
                    type: 4,
                    title: this.$t('resource.video_text') + '2',
                    order: ['text', 'video']
                }
            ],
            videoConfig: {
                videoUrl: '', // 播放地址
                lastPlayTime: '' // 上次播放时间
            }

        };
    },
    methods: {
        getVideoConfig(item) {
            return {
                videoUrl: this.appUrl + item.scpSrcLink, // 播放地址
                lastPlayTime: '' // 上次播放时间
            };
        },
        onlineCalculation(type) {
            this.$axios({
                method: 'GET',
                url: `/app/api/data/kanban/online/${type}/calculate`
            }).then(res => {
                console.log(res);
            });
        },
        back() {
            this.$toast(this.$t('mod_save_record'));
            this.$router.go(-1);
        },
        //  学习心跳
        palpitateTime() {
            this.$axios({
                method: 'POST',
                url: '/app/api/trainee/course/learn/heartbeat',
                data: this.palpitate
            });
        },
        /*保存学习记录*/
        saveRecord(id, leave = false, newId, times) {
            this.$toast(this.$t('mod_save_record'));
            const req = {
                entId: this.$route.params.userEntId,
                itmId: this.$route.params.itmId,
                modId: this.modId,
                startTime: this.startTime,
                tkhId: this.$route.params.tkhId
            };
            if (times) {
                req.codeInputTime = times;
            }
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/course/start_lear_time/${req.modId}`
            }).then(res => {
                console.log(res);
                this.startTime = res.data;
            });

            this.$axios({
                method: 'POST',
                url: `/app/api/trainee/course/module/evaluation`,
                data: req
            }).then(res => {
                if (leave) {
                    return true;
                }
            });
        },
        //获取详细信息
        getFreshModule() {
            this.$axios({
                method: 'GET',
                url: `/app/api/trainee/course/module/detail`,
                params: {
                    itmId: this.$route.params.itmId,
                    modId: this.modId
                }
            }).then(res => {
                if (res && res.status === 200) {
                    this.formData = res.data.smallClassDTO;
                    this.modHangUpTime = res.data.modHangUpTime;
                    this.startTime = res.data.startTime;
                    // 若设置了防挂机间隔时间，则初始化定时器。倒计时结束打开弹窗
                    if (this.modHangUpTime && this.modHangUpTime !== 0) {
                        this.handTime();
                    } else {
                        this.palpitateTime();
                        this.times = setInterval(() => {
                            this.palpitateTime();
                        }, 5000);
                    }
                }
            });
        },
        /**
         * @description: 防挂机间隔定时器
         * @param {*}
         * @return {*}
         */
        handTime() {
            this.handTimes = this.modHangUpTime * 60;
            this.handTimer = setInterval(() => {
                this.handTimes--;
                if (this.handTimes === 0) {
                    clearInterval(this.handTimer);
                    this.player = document.querySelector('video');
                    if (this.player) {
                        this.player.pause();
                    }
                    this.exitFullscreen();
                    this.isHide = true;
                    this.isHandUp = true;
                    this.overTime = true;
                }
            }, 1000);
            this.$once('hook:beforeDestroy', () => {
                clearInterval(this.handTimer);
            });
        },
        /**
         * @description: 防挂机超时处理
         * @param {*}
         * @return {*}
         */
        handleOverTime() {
            this.overTime = true;
            this.isHandUp = false;
            this.$router.go(-1);
        },
        /**
         * @description: 通过防挂机验证，继续学习
         * @param {*}
         * @return {*}
         */
        passCode(times) {
            this.isHandUp = false;
            this.isHide = false;
            this.saveRecord(this.oldTarget, true, times);
            this.handTime();
        },
        exitFullscreen() {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.oRequestFullscreen) {
                document.oCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else {
                var docHtml = document.documentElement;
                var docBody = document.body;
                var videobox = this.player;
                docHtml.style.cssText = '';
                docBody.style.cssText = '';
                videobox.style.cssText = '';
                document.IsFullScreen = false;
            }
        }
    },
    destroyed() {
        this.onlineCalculation('ONLINE_LEARN_DEC');
    },
    mounted() {
        this.onlineCalculation('ONLINE_LEARN_INC');
        this.palpitate.itmId = this.$route.params.itmId;
        this.palpitate.modId = this.$route.params.modId;
        this.palpitate.tkhId = this.$route.params.tkhId;
        // let _this = this;
        this.getFreshModule();
    },
    beforeRouteEnter(to, from, next) {
        next(_this => {
            if (from.path.indexOf('/offline') !== -1) {
                _this.isFromMobile = true;
            }
        });
    },
    beforeRouteLeave(to, from, next) {
        if (!this.overTime) {
            this.saveRecord();
        }
        next();
    },
    beforeDestroy() {
        clearInterval(this.times);
        this.times = null;
    }
};
</script>

<style scoped lang="less">
.s-content{
    position: relative;
    background: #ffffff;
    padding:0 10px;
    height: 100%;
    overflow: hidden;
    .con-box-head{
        border-bottom: 1px solid #dedede;
        padding: 10px 0;
        margin-bottom: 10px;
        h2{
            font-size: 18px;
        }
        .author-msg{
            text-align: right;
            font-size: 14px;
            color: #999;
        }
    }
    .con-box{
        width: 100%;
        height: 100%;
        overflow-y: scroll;
        img {
            max-width: 100%!important;
            height: auto;
        }
        .con-box-img{
            max-width: 100%!important;
            height: auto;
            margin: 10px 0;
        }
        .con-box-video{
            width: 100%!important;
            max-width: 100%!important;
            height: auto;
            margin: 10px 0;
        }
        .con-box-audio{
            width: 100%!important;
            max-width: 100%!important;
            height: 50px;
            margin: 10px 0;
        }
        .con-box-text{
            width: 100%;
            position: relative;
            margin: 10px 0;
            overflow: hidden;
            p{
                line-height: 24px;
            }
        }
    }
}
/deep/.code-popup{
  min-width: 80%;
}
.hideVideo{
  /deep/video{
    display: none;
  }
}
/deep/.van-nav-bar__title {
    margin: 0 10px;
}
</style>
